package com.haoxuer.discover.quartz.data.service.impl;

import com.haoxuer.discover.quartz.data.dao.CronTaskDao;
import com.haoxuer.discover.quartz.data.entity.CronTask;
import com.haoxuer.discover.quartz.data.enums.TaskState;
import com.haoxuer.discover.quartz.data.service.CronTaskService;
import com.haoxuer.discover.quartz.task.HttpJob;
import com.haoxuer.discover.quartz.utils.SchedulerUtils;
import com.haoxuer.discover.data.core.Updater;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.data.page.Order;
import com.haoxuer.discover.data.page.Page;
import com.haoxuer.discover.data.page.Pageable;
import com.haoxuer.discover.data.utils.FilterUtils;

import java.util.List;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by imake on 2017年08月24日14:31:27.
 */


@Scope("prototype")
@Service
@Transactional
public class CronTaskServiceImpl implements CronTaskService {
  
  private CronTaskDao dao;
  
  
  @Override
  @Transactional(readOnly = true)
  public CronTask findById(Long id) {
    return dao.findById(id);
  }
  
  
  @Override
  @Transactional
  public CronTask save(CronTask bean) {
    dao.save(bean);
    return bean;
  }
  
  @Override
  @Transactional
  public CronTask update(CronTask bean) {
    Updater<CronTask> updater = new Updater<CronTask>(bean);
    return dao.updateByUpdater(updater);
  }
  
  @Override
  @Transactional
  public CronTask deleteById(Long id) {
    CronTask bean = dao.findById(id);
    dao.deleteById(id);
    return bean;
  }
  
  @Override
  @Transactional
  public CronTask[] deleteByIds(Long[] ids) {
    CronTask[] beans = new CronTask[ids.length];
    for (int i = 0, len = ids.length; i < len; i++) {
      beans[i] = deleteById(ids[i]);
    }
    return beans;
  }
  
  
  @Autowired
  public void setDao(CronTaskDao dao) {
    this.dao = dao;
  }
  
  @Override
  public Page<CronTask> page(Pageable pageable) {
    return dao.page(pageable);
  }
  
  
  @Override
  public Page<CronTask> page(Pageable pageable, Object search) {
    List<Filter> filters = FilterUtils.getFilters(search);
    if (filters != null) {
      pageable.getFilters().addAll(filters);
    }
    return dao.page(pageable);
  }
  
  @Override
  public Page<CronTask> pageTrigger(Pageable pageable, Object search) {
    Page<CronTask> result = page(pageable, search);
    List<CronTask> tasks = result.getContent();
    if (tasks != null) {
      for (CronTask task : tasks) {
        Scheduler scheduler = SchedulerUtils.getScheduler();
        Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(task.getCron()))
            .withIdentity("trigger" + task.getId(), "group" + task.getId()).build();
        try {
          boolean isexist = scheduler.checkExists(trigger.getKey());
          if (isexist) {
            Trigger temp = scheduler.getTrigger(trigger.getKey());
            task.setNextDate(temp.getNextFireTime());
            Trigger.TriggerState state = scheduler.getTriggerState(trigger.getKey());
            task.setState(TaskState.valueOf(state.name()));
          } else {
            JobDetail jobDetail = JobBuilder.newJob(HttpJob.class)
                .withIdentity("job" + task.getId(), "group" + task.getId()).usingJobData("url", task.getUrl())
                .usingJobData("id", task.getId()).build();
            scheduler.scheduleJob(jobDetail, trigger);
          }
        } catch (SchedulerException e) {
          e.printStackTrace();
        }
      }
      
    }
    return result;
  }
  
  @Override
  public List<CronTask> list(int first, Integer size, List<Filter> filters, List<Order> orders) {
    return dao.list(first, size, filters, orders);
  }
}